const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            tabs: [{ label: '政府组织', name: 'first' }, { label: '党建组织', name: 'second' }],
            activeName: 'first',
            category: [],
            news_tags: [],
            childDataForm: [],
            childDataForm1: [],
            organization1: [],
            organization2: [],
            organization3: [],
            dataForm: {
                News_Category_SerialNumber: 'NC0000000000051',
                Row_Status: '2',
                Environment_MicroScreen: '1',
                Environment_BigScreen: '1',
            },
            save: {
                dataForm: {
                    News_Category_SerialNumber: 'NC0000000000051',
                    Row_Status: '2',
                    Environment_MicroScreen: '1',
                    Environment_BigScreen: '1',
                },
                childDataForm: [],
                childDataForm1: [],
                fileList: [],
            },
            fileList: [],
            notice: [],
            isShow: true,
            update: false
        };
    },
    mounted() {
        let ls_URL = window.location.href;
        let Party_Organization_Activity_SerialNumber = getQueryObject(ls_URL, "Party_Organization_Activity_SerialNumber");// 获取 nodeKey 参数
        if (Party_Organization_Activity_SerialNumber) {
            this.dataForm.Party_Organization_Activity_SerialNumber = Party_Organization_Activity_SerialNumber;
        }
        this.getCategory();
        $.ajax({
            headers: requestHeaders(),
            url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
            type: "GET",
            data: {
                TableName: 'party_organization',
                NodeCode: '',
            },
            success: (data) => {
                this.organization = data; // 直接使用 this
            },
            complete: (XMLHttpRequest) => {
                requestPretreatment(XMLHttpRequest);
            },
            dataType: "json",
        });
    },
    watch: {
        'dataForm.News_SerialNumber'(val) {
            this.save.dataForm.News_SerialNumber = val;
            if (this.dataForm.Party_Organization_Activity_SerialNumber.includes('Par')) {
                this.activeName = 'first'
            } else if (this.dataForm.Party_Organization_Activity_SerialNumber.includes('GA')) {
                this.activeName = 'second'
            } else {
                this.activeName = 'three'
            }
        },
        childDataForm1(val) {
            if (this.action == 'Modify') {
                let arr = [];
                val.forEach(item => {
                    item.name = item.News_Piciture_URL
                    arr.push(item)
                })
                this.fileList = arr
            }
        }
    },
    methods: {
        changeParty(val){
            console.log(val);
            this.dataForm.Data_Belong_Party_Organization_SerialNumber = val;
        },
        getCategory() {
            $.ajax({
                url: absolutepath() + "api/notice.json",
                type: "GET",
                success: (data) => {
                    this.notice = data;
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'news_category',
                    Condition: "Row_Status='0' AND News_Category_SerialNumber='" + this.dataForm.News_Category_SerialNumber + "'",
                },
                success: (data) => {
                    this.category = data; // 直接使用 this
                    this.dataForm.NewsTerminal = data[0].NewsTerminal ? data[0].NewsTerminal.split(",") : [];
                    this.save.dataForm.NewsTerminal = data[0].NewsTerminal ? data[0].NewsTerminal.split(",") : [];
                    this.NewsTerminal = data[0].NewsTerminal ?data[0].NewsTerminal.split(","):[];
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
                type: "GET",
                data: {
                    TableName: 'news_tags',
                    NodeCode: "",
                },
                success: (data) => {
                    this.news_tags = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });

            // getCookie('party') + ',' +  getCookie('unit') + ',' + getCookie('village')

            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/permissionsTree/getPartyOrganizationsTreeByPermissions`,
                type: "GET",
                data: {
                    PartyOrganizationsCode: getCookie('party'), //请求参数
                },
                success: (data) => {
                    this.organization1 = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/permissionsTree/getGovernment_Agencies_TreeByPermissions`,
                type: "GET",
                data: {
                    Government_AgenciesCode: getCookie('unit'), //请求参数
                },
                success: (data) => {
                    this.organization2 = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/permissionsTree/getDistrictTreeByPermissions`,
                type: "GET",
                data: {
                    DistrictCode: getCookie('village'), //请求参数
                },
                success: (data) => {
                    this.organization3 = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        clear(fileList) {
            let SfileList = this.save.fileList;
            this.save.fileList = fileList;
            this.fileList = SfileList;
            this.$refs.ylUpload.handleAdd(SfileList);
        },
        handleClick() {
            let dataForm = this.dataForm;
            let childDataForm = this.childDataForm;
            let childDataForm1 = this.childDataForm1;
            let SdataForm = this.save.dataForm;
            let SchildDataForm = this.save.childDataForm;
            let SchildDataForm1 = this.save.childDataForm1;
            this.save.dataForm = dataForm;
            this.save.childDataForm = childDataForm;
            this.save.childDataForm1 = childDataForm1;
            this.dataForm = SdataForm;
            this.childDataForm = SchildDataForm;
            this.childDataForm1 = SchildDataForm1;
            this.$refs.ylUpload.handleClear();
            this.$nextTick(() => {
                this.update = !this.update;
            })
        },
        handleRemove1(formName) {
            if (this.action === 'Add') {
                if (this[formName].length > 0) {
                    this[formName].pop();
                } else {
                    this.$message({
                        message: '不能在删除了',
                        type: 'warning'
                    })
                }
            } else if (this.action === 'Modify') {
                if (this[formName].filter(item => item.Row_Status != '1').length > 0) {
                    let i = this[formName].filter(item => item.Row_Status != '1').length - 1
                    let obj = this[formName].filter(item => item.Row_Status != '1')[i]
                    if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                        this[formName].pop();
                    } else {
                        this.$confirm('该操作将删除此条数据,是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }).then(() => {
                            this[formName].filter(item => item.Row_Status != '1')[i].Row_Status = '1'
                        }).catch(() => {
                            this.$message({
                                type: 'warning',
                                message: '已取消删除'
                            });
                        });
                    }
                } else {
                    this.$message({
                        message: '不能在删除了',
                        type: 'warning'
                    })
                }
            }
        },
        success(row, res) {
            this.childDataForm1.push({
                uid: row.uid,
                News_SerialNumber: this.dataForm.News_SerialNumber,
                News_Piciture_URL: res.fileName
            })
        },
        remove(row) {
            if (!Object.keys(row).some(item => item.includes('_Original'))) {
                this.childDataForm1 = this.childDataForm1.filter(i => i.uid != row.uid);
            } else {
                let obj = this.childDataForm1.filter(i => i.News_Picture_SerialNumber == row.News_Picture_SerialNumber)[0];
                obj.Row_Status = '1'
            }
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                this.childDataForm1.filter(i => i.Row_Status != '1').forEach((item, index) => {
                    item.Picture_Order = index + 1;
                })
                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        let lJSONObject_ChildData_Options = new Object();
                        lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                        let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                        let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                        // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                        //建立子表结构体
                        let JSONArray_ChildRecord = new Array();
                        JSONArray_ChildRecord = this[ls_ChildDataForm];
                        if (!this[ls_DataForm].Children) {
                            this[ls_DataForm].Children = new Object();
                        }
                        this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                    })
                } catch (error) {

                }
                let dataForm = deepClone(this[ls_DataForm]);
                dataForm.NewsTerminal = dataForm.NewsTerminal.length > 0 ? dataForm.NewsTerminal.join(','):''
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        dataForm.Parent_SerialNumber = this.nodeKey;
                    }
                    dataForm.News_Publish_Datetime = getYMDHMSDate();
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(dataForm);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(dataForm);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);
                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;
                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                if (!lJSONObject_DataSet['Add']) {
                    lJSONObject_DataSet['Add'] = new Object();
                }
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSave",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {
                        window.history.go(-1);
                    }
                    this.loading = false;
                })
                // $.ajax({
                //     headers: requestHeaders(),
                //     url: `${mh}/generalBusiness/generalSave`,
                //     method: "post",
                //     data: {
                //         Data: JSON.stringify(lJSONObject_DataSet),
                //     },
                //     success: (res) => {
                //         if (res.Status == 'success') {
                //             window.history.go(-1);
                //         }
                //     },
                //     complete: (XMLHttpRequest) => {
                //         requestPretreatment(XMLHttpRequest);
                //         this.loading = false;
                //     }
                // });
            }
        },
    },
};


const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-cascader', ylCascader)
app.component('yl-text-editor', ylTextEditor);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
